<template>
  <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑分类' : '新增分类'"
      class="category-dialog"
      width="700px"
      @close="handleClose"
  >
    <div class="dialog-content">
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-position="left"
          label-width="120px"
          size="large"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
              v-model="form.name"
              maxlength="50"
              placeholder="请输入分类名称"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类层级" prop="level">
          <el-radio-group v-model="form.level" @change="handleLevelChange">
            <el-radio :label="1">一级分类</el-radio>
            <el-radio :label="2">二级分类</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.level === 2" label="父分类" prop="parentId">
          <el-select
              v-model="form.parentId"
              placeholder="请选择父分类"
              style="width: 100%"
          >
            <el-option
                v-for="category in firstLevelCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类描述" prop="description">
          <el-input
              v-model="form.description"
              :rows="3"
              maxlength="200"
              placeholder="请输入分类描述"
              show-word-limit
              type="textarea"
          />
        </el-form-item>

        <el-form-item label="排序值" prop="sortOrder">
          <el-input-number
              v-model="form.sortOrder"
              :max="999"
              :min="0"
              placeholder="排序值"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="分类图标" prop="icon">
          <div class="icon-upload">
            <el-upload
                :before-upload="beforeIconUpload"
                :http-request="handleIconUpload"
                :show-file-list="false"
                class="icon-uploader"
            >
              <img v-if="form.icon" :src="form.icon" class="icon-preview"/>
              <el-icon v-else class="icon-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
            <div class="icon-tips">
              <p>建议尺寸：64x64px</p>
              <p>支持格式：JPG、PNG、GIF</p>
              <p>文件大小：不超过2MB</p>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" @click="handleClose">取消</el-button>
        <el-button
            :loading="loading"
            size="large"
            type="primary"
            @click="handleSubmit"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {useCategoryStore} from '@/store/category'


// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  categoryId: {
    type: Number,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// Store
const categoryStore = useCategoryStore()

// 响应式数据
const formRef = ref()
const loading = ref(false)
const firstLevelCategories = ref([])

const form = reactive({
  name: '',
  level: 1,
  parentId: null,
  description: '',
  sortOrder: 0,
  icon: '',
  status: 1
})

const rules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur'}
  ],
  level: [
    {required: true, message: '请选择分类层级', trigger: 'change'}
  ],
  parentId: [
    {required: true, message: '请选择父分类', trigger: 'change'}
  ],
  sortOrder: [
    {required: true, message: '请输入排序值', trigger: 'blur'},
    {type: 'number', min: 0, max: 999, message: '排序值范围为 0-999', trigger: 'blur'}
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.categoryId)

// 监听分类ID变化，加载分类详情
watch(() => props.categoryId, async (newId) => {
  if (newId) {
    await loadCategoryDetail(newId)
  } else {
    resetForm()
  }
}, {immediate: true})

// 方法
const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(form, {
    name: '',
    level: 1,
    parentId: null,
    description: '',
    sortOrder: 0,
    icon: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

const handleLevelChange = (level) => {
  if (level === 1) {
    form.parentId = null
  }
}

const loadCategoryDetail = async (categoryId) => {
  try {
    loading.value = true
    const response = await categoryStore.getCategoryDetail(categoryId)
    if (response.data) {
      Object.assign(form, response.data)
    }
  } catch (error) {
    console.error('加载分类详情失败:', error)
    ElMessage.error('加载分类详情失败')
  } finally {
    loading.value = false
  }
}

const loadFirstLevelCategories = async () => {
  try {
    const response = await categoryStore.getCategoryTree()
    if (response.data) {
      firstLevelCategories.value = response.data.filter(cat => cat.level === 1)
    }
  } catch (error) {
    console.error('加载一级分类失败:', error)
  }
}

const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleIconUpload = async (options) => {
  const file = options.file

  try {
    // 转换为Base64，直接存储到表单中
    const base64 = await fileToBase64(file)
    form.icon = base64
    ElMessage.success('图标选择成功')
  } catch (error) {
    console.error('图标处理失败:', error)
    ElMessage.error('图标处理失败')
  }
}

const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    if (isEdit.value) {
      await categoryStore.updateCategory(props.categoryId, form)
      ElMessage.success('更新成功')
    } else {
      await categoryStore.createCategory(form)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadFirstLevelCategories()
})
</script>

<style scoped>
/* 对话框样式 */
:deep(.category-dialog) {
  border-radius: var(--admin-radius-lg);
  overflow: hidden;
}

:deep(.category-dialog .el-dialog__header) {
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
  padding: var(--admin-space-lg);
}

:deep(.category-dialog .el-dialog__title) {
  font-size: var(--admin-font-lg);
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
}

:deep(.category-dialog .el-dialog__body) {
  padding: var(--admin-space-xl);
}

:deep(.category-dialog .el-dialog__footer) {
  background: var(--admin-bg-secondary);
  border-top: 1px solid var(--admin-border-light);
  padding: var(--admin-space-lg);
}

.dialog-content {
  min-height: 300px;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: var(--admin-space-lg);
}

.el-form-item:last-child {
  margin-bottom: 0;
}

/* 图标上传样式 */
.icon-upload {
  display: flex;
  align-items: flex-start;
  gap: var(--admin-space-md);
}

.icon-uploader {
  border: 2px dashed var(--admin-border-medium);
  border-radius: var(--admin-radius-md);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  background: var(--admin-bg-tertiary);
}

.icon-uploader:hover {
  border-color: var(--admin-primary);
  background: var(--admin-bg-hover);
}

.icon-uploader-icon {
  font-size: var(--admin-font-xl);
  color: var(--admin-text-tertiary);
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
}

.icon-preview {
  width: 80px;
  height: 80px;
  display: block;
  object-fit: cover;
  border-radius: var(--admin-radius-sm);
  border: 1px solid var(--admin-border-light);
}

.icon-tips {
  font-size: var(--admin-font-xs);
  color: var(--admin-text-tertiary);
  line-height: var(--admin-line-height-md);
  padding: var(--admin-space-sm);
  background: var(--admin-bg-tertiary);
  border-radius: var(--admin-radius-sm);
  border-left: 3px solid var(--admin-info);
}

.icon-tips p {
  margin: 0;
  margin-bottom: var(--admin-space-xs);
}

.icon-tips p:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: center;
  display: flex;
  justify-content: center;
  gap: var(--admin-space-md);
}

.dialog-footer .el-button {
  min-width: 120px;
  font-weight: var(--admin-font-medium);
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.category-dialog) {
    width: 90vw !important;
    margin: var(--admin-space-md);
  }

  .dialog-footer {
    flex-direction: column;
  }

  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>
